package ru.sushka.lunch.dao.psql;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import ru.sushka.lunch.enitiy.Order;

public class PsqlOrderDao extends PsqlDao<Order>{

    private final String tableName = "orders";
    
    @Override
    protected String getTableName() {
        return tableName;
    }

    @Override
    protected String getSelectSqlQuery(int id) {
        return "select * from " + tableName + " where id = " + id;
    }

    @Override
    protected String getDeleteSqlQuery(int id) {
        return "delete from " + tableName + " where id = " + id;
    }

    @Override
    protected String getInsertSqlQuery(Order persistence) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(persistence.getDate().getTime());
        return "insert into " + tableName + "(customer_id, menuitem_id, order_date, menuitem_count) values(" + 
                                persistence.getCustomerId() + "," + 
                                persistence.getMenuItemId() + ",'" + 
                                date+ "'," + 
                                persistence.getCount() +")";
    }

    @Override
    protected String getUpdateSqlQuery(Order persistence) {
        //ISO 8601
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(persistence.getDate().getTime());
        return "update customers set id=" + persistence.getId() + 
                                        "customer_id ="+persistence.getCustomerId()+","+
                                        "menuitem_id ="+persistence.getMenuItemId()+", "+
                                        "order_date  ='"+date+"', "+
                                        "menuitem_count  ="+persistence.getCount()+" "+
                                        "where id=" + persistence.getId();
    }

    @Override
    protected Order parseResultSet(ResultSet rs) throws SQLException{
        int id = rs.getInt(1);
        int customerId = rs.getInt(2);
        int menuItemId = rs.getInt(3);
        Calendar orderDate = Calendar.getInstance();
        orderDate.setTime(rs.getDate(4));
        int count = rs.getInt(5);
        Order order = new Order(menuItemId, customerId, count, orderDate);
        order.setId(id);
        return order;
    }

}
